package com.kingtao.protocol;

import com.kingtao.message.Message;
import com.kingtao.util.Config;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author: kingtao
 * @Date: 2023-08-23-15:58
 * @Description:
 */
@Slf4j
@ChannelHandler.Sharable
public class MessageCodec extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, List<Object> list) throws Exception {
        ByteBuf byteBuf = channelHandlerContext.alloc().buffer();
        //  4 字节 序列化方式
        byteBuf.writeInt(Config.getSerializerAlgorithm().ordinal());
        //  4 字节 类型
        byteBuf.writeInt(message.getMessageType());

        byte[] bytes = Config.getSerializerAlgorithm().serializer(message);
        //  4 字节 长度
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
        list.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int serializerType = byteBuf.readInt();
        int messageType = byteBuf.readInt();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes, 0, length);

        Serializer.Algorithm algorithm = Serializer.Algorithm.values()[serializerType];

        Class<? extends Message> messageClass = Message.getMessageClass(messageType);
        Object message = algorithm.deserializer(messageClass, bytes);

        list.add(message);
    }
}
